<template>
  <el-popover
    trigger="click"
    :visible="visible"
    :title="title"
    :width="width"
    @after-leave="state.modelValue = props.value"
  >
    <slot>
      <el-input
        v-model="state.modelValue"
        type="textarea"
        :minlength="minlength"
        :maxlength="maxlength"
        :autosize="{ minRows: 4, maxRows: 4 }"
        :placeholder="placeholder"
      />
    </slot>
    <p class="text-[12px] text-[#999999] pl-2 mt-2">
      {{ !tips ? `备注: 长度显示${maxlength}个字符` : tips }}
    </p>
    <div class="flex justify-end mt-2">
      <el-button type="default" @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSubmit">保存</el-button>
    </div>
    <template #reference>
      <slot name="reference">
        <el-button size="small" link>
          <edit color="#2E61EE" class="w-[16px] h-[16px]" />
        </el-button>
      </slot>
    </template>
  </el-popover>
</template>

<script setup lang="ts">
import { Edit } from '@element-plus/icons-vue'

interface IProps {
  title: string
  visible: boolean
  value?: string
  width?: string
  placeholder?: string
  tips?: string
  maxlength?: number
  minlength?: number
}

interface IEmit {
  (event: 'cancel'): void
  (event: 'submit', value: string): void
  (event: 'update:visible', value: boolean): void
}

const emit = defineEmits<IEmit>()
const props = withDefaults(defineProps<IProps>(), {
  width: '350',
  placeholder: '请输入',
  maxlength: 200,
  minlength: 0
})

const state = reactive({
  modelValue: ref(props.value)
})

const handleCancel = () => {
  emit('cancel')
  emit('update:visible', false)
}

watch(
  () => props.value,
  val => (state.modelValue = val)
)

const handleSubmit = () => {
  if (!state.modelValue && props.minlength > 0) {
    ToastUtils.error('请输入内容')
    return
  }
  if (
    state.modelValue!.length < props.minlength ||
    state.modelValue!.length > props.maxlength
  ) {
    ToastUtils.error(`请输入${props.minlength}-${props.maxlength}个字符`)
    return
  }
  emit('submit', state.modelValue!)
  emit('update:visible', false)
}
</script>

<style lang="scss" scoped></style>
